import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";
import {useTokenStore} from "@/stores/token.js";

const service = axios.create({
  baseURL: "http://localhost:8080"
});


//axios的请求拦截器
service.interceptors.request.use(function (config) {
  const tokenStore = useTokenStore();
  //如果不是登录请求，就在请求头中添加token
  if (!config.url.startsWith("/login")) {

    //将store中的token赋值给请求头
    config.headers.token = tokenStore.tokenStr;
    // console.log(config);
  }
  return config;
}, function (error) {
  //对请求错误做些什么
  return Promise.reject(error);
});



//axios的响应拦截器
service.interceptors.response.use(resp => {
  // console.log(resp.headers);
  //获取续期的jwt
  let token = resp.headers.token;

  const tokenStore = useTokenStore();
  tokenStore.update(token);
  return resp.data;
}, error => {
  if (error.status == 403) {
    ElMessage.error({
      message: '令牌错误，请重新登录',
      duration: 1200,
      onClose: function () {
        //删除store中的token设置为初值
        const tokenStore = useTokenStore();
        tokenStore.$reset();
        //调转到主页面
        router.push("/login");
      }
    });
  }
});
export default service;